package main

import (
	"fmt"
	"log"
	"net/http"
	//"github.com/Sirupsen/logrus"
	"github.com/gorilla/sessions"
)

const (
	//SessionName to store session under
	SessionName = "go-sessions-demo"
)

var (
	sessionStore sessions.Store
	//log          = logrus.WithField("cmd", "go-sessions-demo")
)

type user struct{
	Name string
	Password string
}
func Select(n,p string) []user{
	sql := "select * from user where name =? and password =?"
	rowz,err:=Dql(sql,n,p)
	if err!=nil{
		fmt.Println(err)
		return nil
	}
	users:=make([]user,0)
	for rowz.Next(){
		var u user
		rowz.Scan(&u.Name,&u.Password)
		//fmt.Println(u.name)
		users=append(users,u)
	}
	CloseConn()
	return users
}

func handleSessionError(w http.ResponseWriter, err error) {
	//log.WithField("err", err).Info("Error handling session.")
	http.Error(w, "Application Error", http.StatusInternalServerError)
}

func home(w http.ResponseWriter, r *http.Request) {
	session, err := sessionStore.Get(r, SessionName)
	if err != nil {
		handleSessionError(w, err)
		return
	}

	username, found := session.Values["username"]
	if !found || username == "" {
		http.Redirect(w, r, "/public/login.html", http.StatusSeeOther)
		//log.WithField("username", username).Info("Username is empty/notfound, redirecting")
		return
	}

	w.Header().Add("Content-Type", "text/html")
	fmt.Fprintf(w, "<html><body>Hello %s<br/><a href='/logout'>Logout</a></body></html>", username)
}

func login(w http.ResponseWriter, r *http.Request) {
	username := r.FormValue("username")
	password := r.FormValue("password")
	u := Select(username,password)
	//fmt.Println(u.Name)

	//log.WithFields(logrus.Fields{"username": username, "password": password}).Info("Received login request.")

	// Normally, these would probably be looked up in a DB or environment
	if len(u)>0 {
		session, err := sessionStore.Get(r, u[0].Name)
		if err != nil {
			handleSessionError(w, err)
			return
		}

		session.Values["username"] = username
		if err := session.Save(r, w); err != nil {
			handleSessionError(w, err)
			return
		}

		//log.WithField("username", username).Info("completed login & session.Save")
	}

	http.Redirect(w, r, "/", 303)
}

func logout(w http.ResponseWriter, r *http.Request) {
	session, err := sessionStore.Get(r, SessionName)
	if err != nil {
		handleSessionError(w, err)
		return
	}

	session.Values["username"] = ""
	if err := session.Save(r, w); err != nil {
		handleSessionError(w, err)
		return
	}

	//log.Info("completed logout & session.Save")
	http.Redirect(w, r, "/", 302)
}

func main() {
	//ek, err := determineEncryptionKey()
	//if err != nil {
	//	log.Fatal(err)
	//}
	//port := os.Getenv("PORT")
	//if port == "" {
	//	//log.WithField("PORT", port).Fatal("$PORT must be set")
	//}
	key := []byte("super-secret-key")

	sessionStore = sessions.NewCookieStore(
		key,
	)

	http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./public"))))
	http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "Not Found", http.StatusNotFound)
	})
	http.HandleFunc("/login", login)
	http.HandleFunc("/logout", logout)
	http.HandleFunc("/", home)

	log.Println(http.ListenAndServe(":9090", nil))
}
